<?php

namespace App\Services;

use App\Models\User;
use Illuminate\Support\Facades\Redis;

/**
 * Copyright (C), 2021-2021, Shall Buy Life info. Co., Ltd.
 * FileName: ${FILE_NAME}
 * Description: 说明
 *
 * @author lwl
 * @Create Date    2021/11/8 11:04
 * @Update Date    2021/11/8 11:04 By lwl
 * @version v1.0
 */
class RedisService
{
    /**
     * FunctionName：publish
     * Description：生产者发布
     * Author：lwl
     */
    public function publish()
    {
        $editUserChannel = config('common.edit_user_channel.0');
        $userId = 1;
        try {
            $data = ['user_id' => $userId];
            Redis::publish($editUserChannel, json_encode($data));
        } catch (\Exception $exception) {
            echo $exception->getMessage();
        }
    }

    /**
     * FunctionName：subScribe
     * Description：消费者订阅
     * Author：lwl
     */
    public function subScribe()
    {
        set_time_limit(0);
        ini_set('default_socket_timeout', -1);
        try {
            $channels = config('common.edit_user_channel');
            echo 'Start Subscription' . "\n";
            Redis::subscribe($channels, function ($json, $message) {
                $data = json_decode($json, 1);
                User::edit($data['user_id'], ['sex' => 1]);
            });
        } catch (\Exception $e) {
            echo $e->getMessage();
        }
    }
}
